//非会员产品列表
var $customerProductTable = $('#customerProductTableList');
let tag = $('#tag').val();
$(function (){
    customerProductTableListInit();
    checkPer();
});


//用户系统隐藏会员卡信息
function checkPer() {
    if (tag == 2) { //用户端
        $customerProductTable.bootstrapTable('hideColumn', 'operate');
        $customerProductTable.bootstrapTable('hideColumn', 'shelfStatus');
        $customerProductTable.bootstrapTable('hideColumn', 'shelfStatus');
    }else{
        document.getElementById("addCustomerProduct").style.display = "block";
    }
}

/**
 * 初始化非会员产品列表
 */
function customerProductTableListInit(){
    //先销毁表格
    $customerProductTable.bootstrapTable('destroy');
    $customerProductTable.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: '/customerProduct/selectCustomerProductList',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        // sortOrder: "desc",//排序方式
        // sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        // serverSort: true,
        uniqueId: 'customerProductId',
        idField: 'customerProductId',
        pageSize: globalPageSize,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: globalPageList,//可供选择的每页的行数

        fixedColumns: true,     // 冻结列
        fixedNumber: 1,         // 左侧固定列
        fixedRightNumber: 2,    // 右侧固定列

        queryParams: queryParams,//查询参数
        columns: [
            {title: '主键', field: 'customerProductId', visible: false},
            {title: '序号', field: 'index', align: 'left', valign: 'middle', width: '60', formatter: indexFormat},
            {title: '产品名称',field: 'productName', sortable: true,align: 'left', valign: 'middle', formatter: productNameFormat},
            {title: '产品编码', field: 'productCode', align: 'left', valign: 'middle'},
            // {title: '产品分类', field: 'productCategories', sortable: true,align: 'left', valign: 'middle'},
            {title: '产品标签', field: 'productTag', sortable: true,align: 'left', valign: 'middle'},
            {title: '服务分类', field: 'serviceClassification', sortable: true, align: 'left',valign: 'middle'},
            {title: '产品原价', field: 'productOriginalPrice', sortable: true,align: 'left',valign: 'middle'},
            {title: '产品单价', field: 'productUnitPrice', sortable: true,align: 'left',valign: 'middle'},
            {title: '产品会员价', field: 'productMemberPrice', sortable: true,align: 'left', valign: 'middle'},
            {title: '业绩换算比例', field: 'performanceConversionRatio', sortable: true,align: 'left', valign: 'middle'},
            // {title: '产品描述', field: 'productDesc',align: 'left',valign: 'middle'},
            // {title: '专题ID', field: 'topicId',align: 'left',valign: 'middle'},
            // {title: '学习期数', field: 'studyPeriod',align: 'left',valign: 'middle'},
            {title: '兑换方式', field: 'exchangeMethodValue', sortable: true,align: 'left',valign: 'middle'},
            {title: '上架状态', field: 'shelfStatus', sortable: true, align: 'left', valign: 'middle',formatter: shelfStatusFormat},
            // {title: '上架时间', field: 'shelfTime',align: 'left',valign: 'middle'},
            // {title: '下架时间', field: 'offShelfTime',align: 'left',valign: 'middle'},
            // {title: '会员卡级别', field: 'membershipCardLevel', sortable: true, align: 'left', valign: 'middle'},
            // {title: '会员卡类型', field: 'membershipCardType', sortable: true, align: 'left', valign: 'middle',formatter: memberShipCardTypeFormat},
            // {title: '产品说明', field: 'productManual',align: 'left', valign: 'middle'},
            // {title: '创建人', field: 'createPeopleName',align: 'left', valign: 'middle'},
            {title: '创建时间', field: 'createTm', sortable: true, align: 'left', valign: 'middle'},
            // {title: '更新时间', field: 'updateTm', align: 'left', valign: 'middle'},
            // {title: '产品有效期', field: 'productPeriodValidity', align: 'left', valign: 'middle'},
            {title: '操作', field:'operate', align:'left', width: '96', events:operateEvents, formatter: genderOpt},
            {title: '是否上架',field:'shelfStatus',align:'right', sortable: true, width: '82', formatter: operateShelfStatusFormat}
        ],
        responseHandler: function (result) {
            if(result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            // table列可拖动宽度
            $('.JCLRgrips').remove();
            $('#customerProductTableList').css({
                minWidth: $('#customerProductTableList').width()
            }).colResizable({
                resizeMode: 'overflow',
                liveDrag: true,
                gripInnerHtml: "<div class='grip'></div>",
                draggingClass: "dragging",
                disabledColumns: [0, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],      // 禁止拖动的列
                postbackSafe: true,                                         // 刷新后保持拖动的宽度
                partialRefresh: true,                                       // 刷新表格之后继续保持可拖动功能
                flush: true,
                minWidth: 80,
                /*onResize: function () {
                }*/
            });
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}

/**
 * 拼接产品列表查询条件参数
 */
function queryParams(params){
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式
    params.tag = tag;

    //产品列表搜索条件
    params.productName = $.trim($('#productName').val());//产品名称
    params.productCode = $.trim($('#productCode').val());//产品编码
    return params;
}

/**
 * --列表序列号
 */
function indexFormat(value, row, index) {
    return index + 1;
}

/**
 * 产品名称自定义
 * */
function productNameFormat(value, row, index) {
    // console.log(value, row, index);
    var html = '<a href="#detailModel" data-toggle="modal">' + value + '</a>';
    return html;
}

/**
 * 自定义操作列内容
 */
function genderOpt(value, row, index) {
    // let html = '<button class="btn btn-default" id="detail" data-target="#detailModel"><i class="mdi mdi-eye"></i>详情</button>';
    var html = '<button class="btn btn-default" id="edit" data-target="#editModel"><i class="mdi mdi-grease-pencil"></i>编辑</button>';
    return html;
}

/**
 * 自定义操作列事件
 */
window.operateEvents = {
    //编辑点击事件
    'click #edit': function(e, value, row, index) {
        parent.$(parent.document).data('multitabs').create({
            iframe: true,
            title: '产品编辑',
            url: "/front/productManager/editProduct?customerProductId=" + row.customerProductId + "&tag=" + tag
        }, true);
    }
};

/**
 * 产品上/下架状态格式化
 * @param value
 * @param row
 * @param index
 */
function shelfStatusFormat(value, row, index){
    if(value == null || value == undefined) {
        return '';
    }else if(value == 0) {
        return '待定';
    } else if (value == 3) {
       return '已上架';
    }else if(value == 2){
        return "已下架";
    }
}

/**
 * 兑换方式格式化
 * @returns {*}
 */
/*
function exchangeMethodFormat(value, row, index){
    if(value == null || value == undefined) {
        return '';
    }
    return selectDictionaryByCode(14,value);
}
*/

/**
 * 会员发卡类型格式化
 */
function memberShipCardTypeFormat(value, row, index){
    if(value == null || value == undefined) {
        return '';
    }
    return selectDictionaryByCode(13,value);
}

//根据字典大分类、小分类查询字典数据
/*function selectDictionaryByCode(typeCode,dictCode){
    var memberShipCardType;
    $.ajax({
        type: "post",
        url: "/dictionary/selectDictionaryByCode",
        data: {
            typeCode: typeCode,
            dictCode: dictCode
        },
        dataType: 'json',
        async: false,
        success: function (data, status) {
            if (data.code == '000000') {
                memberShipCardType = data.data.dictName;
            } else {
                $.alert(data.message);
            }
        },
        error: function () {
        }
    });
    return memberShipCardType;
}*/

/**
 * 产品上/下架操作
 */
function operateShelfStatusFormat(value, row, index){
    var is_checked = '';
    let shelfStatus = '';
    var newShelfStatus;
    if(value == null || value == undefined) {
        return '';
    }else if(value == 0 || value == 2) {
        is_checked = '';
        newShelfStatus = 1;
    } else if (value == 3) {
        is_checked = 'checked="checked"';
        newShelfStatus = 2;
    }
    var shelfStatusHtml = '<label class="lyear-switch switch-solid switch-success">' +
        '<input type="checkbox" id="shelfStatus' + row.customerProductId  + '" ' + is_checked + '>' +
        '<span onClick="updateShelfStatus(\'' + row.customerProductId + '\', \'' + newShelfStatus + '\')"></span>' +
        '</label>';
    return shelfStatusHtml;
}

/**
 * 产品上/下架操作调用后端
 * @param customerProductId
 * @param shelfStatus
 */
function updateShelfStatus(customerProductId,shelfStatus){
    var confirmMessage = '';
    if (shelfStatus == 1) {
        confirmMessage = "确定上架吗？";
    } else {
        confirmMessage = "确定下架吗？";
    }
    $.alert({
        title: '提示',
        content: confirmMessage,
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary',
                action: function () {
                    $.ajax({
                        type: "post",
                        url: "/customerProduct/updateShelfStatus",
                        // contentType: 'application/json;charset=UTF-8',
                        data: {
                            customerProductId: customerProductId,
                            shelfStatus: shelfStatus
                        },
                        dataType: 'json',
                        success: function (data, status) {
                            if (data.code == '000000') {
                                $customerProductTable.bootstrapTable('refreshOptions', {pageNumber: 1});
                            } else {
                                $.alert(data.message);
                                $customerProductTable.bootstrapTable('refreshOptions', {pageNumber: 1});
                            }
                        },
                        error: function () {
                            $.alert('修改失败，请稍后再试!');
                            $customerProductTable.bootstrapTable('refreshOptions', {pageNumber: 1});
                        }
                    });
                }
            },
            cancel: {
                text: '取消',
                action: function () {
                    if(shelfStatus == 1){
                        $("#shelfStatus" + customerProductId).prop('checked',true);
                    }else {
                        $("#shelfStatus" + customerProductId).prop('checked',false);
                    }
                }
            }
        }
    });
}

/**
 * 产品列表--搜索点击事件
 */
function searchCustomerProductTableList(){
    $customerProductTable.bootstrapTable('refreshOptions', {pageNumber: 1});
}

/**
 * 新增产品点击事件
 */
function addCustomerProduct(){
    parent.$(parent.document).data('multitabs').create({
        iframe : true,
        title : '新增非会员产品',
        url : "/front/productManager/addProduct"
    }, true)
}
